﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class DiceController : MonoBehaviour, IEventListener
{
    private Animator Anim;

    public DiceData Data { get; set; }

    private GameObject SpareObject;

    private void Awake()
    {
        //Initiate();
        //EventNodeCore.GetInstance().AttachEventListener(EventDef.GroundStateChange, this);
        //EventNodeCore.GetInstance().AttachEventListener(EventDef.CubeRotate, this);
    }
    private void OnEnable()
    {
        Initiate();
        //Debug.LogWarning(Data.Controller + "" + gameObject.GetHashCode());
    }
    private void OnDisable()
    {
        MapData.Instance.Unregiste(Data);
    }
    private void OnDestroy()
    {
        //EventNodeCore.GetInstance().DetachEventListener(EventDef.GroundStateChange, this);
        //EventNodeCore.GetInstance().DetachEventListener(EventDef.CubeRotate, this);
    }
    /// <summary>
    /// 设置SetObjectOfGround，不填参数则设为null，返回是否为非null
    /// </summary>
    /// <param name="objectOfGround"></param>
    /// <returns></returns>
    public bool SetObjectOfGround(GameObject objectOfGround = null)
    {
        Data.ObjectOfGround = objectOfGround;
        if (objectOfGround)
        {
            return true;
        }
        else return false;
    }
    /// <summary>
    /// 翻转
    /// </summary>
    /// <param name="obj"></param>
    /// <param name="type"></param>
    public void Flip()
    {
        if (Data.ObjectOfGround)
            SpareObject = Data.ObjectOfGround;
        RegistAction(1);
        Anim.SetTrigger("Flip" + 1.ToString());
        //Debug.Log("翻转第" + gameObject.name + "面, 类型： " + type);
    }
    /// <summary>
    /// 翻转完成
    /// </summary>
    public void FlipDone()
    {
        //Debug.Log("翻面完成");
        RegistAction(-1);
        if (SpareObject)
            Destroy(SpareObject);
        SpareObject = null;
        if (transform.GetChild(0).childCount > 1)
        {
            for (int i = 0; i < transform.GetChild(0).childCount; i++)
            {
                if (transform.GetChild(0).GetChild(i).tag != "Dice" && transform.GetChild(0).GetChild(i).gameObject.activeSelf)
                {
                    FlushChild(transform.GetChild(0).GetChild(i).gameObject);
                }
            }
        }
    }
    /// <summary>
    /// 初始化方法,绑定动画、设置方向、记录方块坐标
    /// </summary>
    public void Initiate()
    {
        if (!Anim)
            Anim = transform.GetComponentInChildren<Animator>();
        FlushData();
        RegisteDice();

    }
    /// <summary>
    /// 注册骰子
    /// </summary>
    public void RegisteDice()
    {
        if (Data != null)
            MapData.Instance.Registe(Data);
    }

    /// <summary>
    /// 刷新骰子数据（自动化）
    /// </summary>>
    public void FlushData()
    {
        if (Data == null)
        {
            Data = new DiceData();
        }

        if (Data.Surface == null)
            if (transform.parent)
                if (transform.parent.GetComponent<SurfaceController>())
                {
                    Data.Surface = transform.parent.GetComponent<SurfaceController>().Data;
                }

        Data.GroundTowards = RotateBase.ReturnAxis((transform.GetChild(0).position - transform.position).normalized);

        if (transform.GetChild(0).childCount > 1)
        {
            for (int i = 0; i < transform.GetChild(0).childCount; i++)
            {
                if (transform.GetChild(0).GetChild(i).tag != "Dice" && transform.GetChild(0).GetChild(i).gameObject.activeSelf)
                {
                    FlushChild(transform.GetChild(0).GetChild(i).gameObject);
                }
            }
        }
        else FlushChild();

        Data.Controller = this;

        Data.Obj = gameObject;

        Data.DiceCoordinate = transform.position;
        if (Data.Surface != null)
            name = string.Concat("Dice" + (Data.DiceCoordinate - Data.Surface.Index - Data.Surface.Cube.Index).ToString());
        else
            name = string.Concat("Dice" + Data.DiceCoordinate + "." + Data.GroundTowards);
    }
    /// <summary>
    /// 刷新地面上的物体
    /// </summary>
    public bool FlushChild(GameObject child = null)
    {
        if (child != null)
        {
            Data.ObjectOfGround = child;
            return true;
        }
        //if (transform.GetChild(0).childCount > 0)
        //{
        //    for(int i = 0; i < transform.GetChild(0).childCount; i++)
        //    {
        //        if(transform.GetChild(0).GetChild(i).tag != "Dice" && transform.GetChild(0).GetChild(i).gameObject.activeSelf)
        //        {
        //            Data.ObjectOfGround = transform.GetChild(0).GetChild(i).gameObject;
        //            return true;
        //        }                
        //    }
        //}
        Data.ObjectOfGround = null;
        return false;
    }

    /// <summary>
    /// 判断此dice能否翻转，可以就返回true
    /// </summary>
    /// <returns></returns>
    public bool CanFlip(GameObject bug = null)
    {
        if (Data.ObjectOfGround != null)
        {
            if (Data.ObjectOfGround.activeSelf)
            {
                if (Data.ObjectOfGround.tag != "Player" && Data.ObjectOfGround.tag != "Block" && Data.ObjectOfGround.tag != "EditorOnly" && Data.ObjectOfGround.tag != "Untagged")
                {
                    Debug.LogWarning(false + "" + Data.DiceCoordinate + "" + Data.GroundTowards);
                return false;
                }
            }
        }
        Debug.LogWarning(true + "" + Data.DiceCoordinate + "" + Data.GroundTowards);
        return true;
    }

    public int EventPriority()
    {
        return 0;
    }

    ///// <summary>
    ///// 如果子物体不为空就发送不翻转信号
    ///// </summary>
    ///// <param name="id"></param>
    ///// <param name="param1"></param>
    ///// <param name="param2"></param>
    ///// <returns></returns>
    //public bool HandleEvent(int id,object param1,object param2)
    //{
    //    switch (id)
    //    {
    //        case EventDef.GroundStateChange:
    //            //Debug.LogError(Data.ObjectOfGround != null && Data.ObjectOfGround.activeSelf == true);
    //            if (Data.ObjectOfGround != null && Data.ObjectOfGround.activeSelf == true)
    //            {
    //                //Debug.LogError(Data.ObjectOfGround.tag != "Player" && Data.ObjectOfGround.tag != "Block");
    //                if (Data.ObjectOfGround.tag != "Player" && Data.ObjectOfGround.tag != "Block")
    //                {
    //                    //Debug.LogWarning(Data.ObjectOfGround.name+"子物体");
    //                    EventNodeCore.GetInstance().SendMessage(EventDef._CanCubeRotate, false);
    //                }
    //            }
    //            break;
    //        //case EventDef.CubeRotate:
    //            //MapManager.Instance.SpawnObj(Data,p);
    //            //break;

    //    }

    //    return false;
    //}

    public bool HandleEvent(int id, object param1, object param2)
    {
        return false;
    }

    private void RegistAction(int IsR)
    {
        EventNodeCore.GetInstance().HandleEvent(EventDef.Action * IsR, null, null);
    }

    /// <summary>
    /// 生成新的面上的物体 
    /// </summary>
    public GameObject SpawnObj(string prefabname)
    {
        return MapManager.Instance.SpawnObj(Data, prefabname);
    }
}